import React, { useEffect, useState } from 'react'
import { Space, Table, Tag } from 'antd';
import type { FormProps } from 'antd';
import { Button, Form, Input, Checkbox, Select } from 'antd';
import type { PopconfirmProps } from 'antd';
import { message, Popconfirm } from 'antd';
import { Drawer } from 'antd';
import type { TableProps } from 'antd';
import {
  PlusOutlined,
  DeleteTwoTone

} from '@ant-design/icons';
import http from '../../api/https'
function Index() {
  const [form] = Form.useForm();
  const [forms] = Form.useForm();
  const [data, setData] = useState([])
  const [total, setTotal] = useState(0)
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [title, setTitle] = useState([])
  const [tag, setTag] = useState([])
  const [delId, setDelId] = useState()
  const [open, setOpen] = useState(false);
  const [flag, setFlag] = useState(false);

  const getdata = () => {
    const params = { page, pageSize }
    if (title) params.keyword = title
    if (tag) params.tag = tag
    http.get("/article/list", {
      params
    }).then((res) => {
      console.log(res);
      if (res.status === 200) {
        setData(res.data.rows)
        setTotal(res.data.count)
      }

    })

  }
  useEffect(() => {
    getdata()
  }, [page, pageSize, title, tag])
  interface DataType {
    key: string;
    name: string;
    age: number;
    address: string;
    tags: string[];
  }

  const columns: TableProps<DataType>['columns'] = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '用户名',
      dataIndex: 'content',
      key: 'content',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '性别',
      dataIndex: 'viewCount',
      key: 'viewCount',
      render: (text) => {
        return text == 0 ? <span style={{ color: 'red' }}>男</span> : "女"
      },
    },
    {
      title: '昵称',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '手机号',
      dataIndex: 'createdAt',
      key: 'createdAt',
    },
    {
      title: '邮箱',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
    },
    {
      title: '标签',
      key: 'tags',
      dataIndex: 'tags',
      render: (_, { tags }) => (
        <>
          {tags.map((tag) => {
            let color = tag.name.length > 5 ? 'geekblue' : 'green';

            return (
              <Tag color={color} key={tag.name}>
                {tag.name.toUpperCase()}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: '状态',
      dataIndex: 'viewCount',
      key: 'viewCount',
      render: (text) => {
        return text == 0 ? <span style={{ color: 'red' }}>禁用</span> : "女"
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button>编辑</Button>
          <Popconfirm
            title="操作提示"
            description="您确定要删除吗?"
            onConfirm={() => confirm(record.id)}
            onCancel={cancel}
            okText="确定"
            cancelText="取消"
          >
            <Button danger>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 分页
  const fenYe = (pages, pageSizes) => {
    setPageSize(pageSizes)
    setPage(pages)
  }
  type FieldType = {
    username?: string;
    password?: string;
    remember?: string;
  };

  const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
    console.log('Success:', values);
    setTitle(values.title)
    setTag(values.tag)
  };
  const reactList = () => {
    form.resetFields()
    setTag("")
    setTitle("")
  }

  const confirm: PopconfirmProps['onConfirm'] = (e) => {
    console.log(e);

    const shan = data.filter((t) => t.id !== e)
    setData(shan)
    message.success('删除成功');
  };
  const cancel: PopconfirmProps['onCancel'] = (e) => {
    console.log(e);
    message.error('Click on No');
  };
  const rowlist = (e) => {
    setDelId(e)
  }
  const delList = () => {
    const shan = data.filter((t) => !delId.includes(t.id))
    setData(shan)
  }
  const add = () => {
    setOpen(true)
    setFlag(true)
  }
  const onClose = () => {
    setOpen(false);
  };
  const onFinishOk = () => {
    const { title, content } = forms.getFieldsValue()
    http.post('/article', {
      title,
content,
tagList:["HTTP"],
categoryList:["HTTP"],
"authorId":47529555
     
    }).then((res) => {
      if (res.status === 200) {
        getdata()
        alert('新增成功')
        setOpen(false)
        forms.resetFields()
      }
    })
  }



  return (
    <div>
      <Form
        form={form}
        layout="inline"
        name="basic"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}

        initialValues={{ remember: true }}
        onFinish={onFinish}

        autoComplete="off"
      >
        <Form.Item
          label="用户名">
          <Input />
        </Form.Item>


        <Form.Item label="性别" >
          <Input />
        </Form.Item>

        <Form.Item
          label="昵称"
          name="title"

        >
          <Input />
        </Form.Item>

        <Form.Item label="手机号" >
          <Input />
        </Form.Item>
        <Form.Item label="邮箱" >
          <Input />
        </Form.Item>

        <Form.Item
          label="标签"
          name="tag"

        >
          <Input />
        </Form.Item>

        <Form.Item
          label="状态"
          name="viewCount">
          <Select
            defaultValue="请选择"
            style={{ width: 120 }}

            options={[
              { value: 'jack', label: '开启' },
              { value: 'lucy', label: '禁用' },

            ]}
          />
        </Form.Item>




        <Form.Item label={null}>
          <Button type="primary" onClick={reactList}>
            重置
          </Button>
        </Form.Item>

        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">
            搜索
          </Button>
        </Form.Item>
      </Form>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'end' }}>
        <Button onClick={add}><PlusOutlined />新增</Button>
        <Button onClick={delList}><DeleteTwoTone />批量删除</Button>
      </div>
      <Table<DataType>
        rowKey="id"
        columns={columns}
        dataSource={data}
        pagination={{
          total: total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `总 ${total} 条`,
          onChange: fenYe
        }}
        rowSelection={{
          type: "checkbox",
          onChange: rowlist
        }}
      />
      <Drawer
        title={flag ? '新增' : '编辑'}
        closable={{ 'aria-label': 'Close Button' }}
        onClose={onClose}
        open={open}
      >
        <Form

          form={forms}
          name="basic"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}

          initialValues={{ remember: true }}
          onFinish={onFinishOk}

          autoComplete="off"
        >
          <Form.Item
            label="用户名"
            name="content"
            rules={[{ required: true, message: '不能为空!' }]}
          >
            <Input />
          </Form.Item>


          <Form.Item label="性别" >
            <Checkbox>男</Checkbox>
            <Checkbox>女</Checkbox>
          </Form.Item>

          <Form.Item
            label="昵称"
            name="title"
            rules={[{ required: true, message: '不能为空!' }]}

          >
            <Input />
          </Form.Item>

          <Form.Item label="手机号" >
            <Input />
          </Form.Item>
          <Form.Item label="邮箱" >
            <Input />
          </Form.Item>

          <Form.Item
            label="标签"
            name="tag"

          >
            <Input />
          </Form.Item>

          <Form.Item
            label="状态"
           
         
          >
            <Checkbox>开启</Checkbox>
            <Checkbox>禁用</Checkbox>
          </Form.Item>
          <Form.Item
            label="用户角色"


          >
            <Input />
          </Form.Item>




          <Form.Item label={null}>
            <Button type="primary" htmlType="submit">
              取消
            </Button>
          </Form.Item>

          <Form.Item label={null}>
            <Button type="primary" htmlType="submit">
              确定
            </Button>
          </Form.Item>
        </Form>
      </Drawer>
    </div >
  )
}

export default Index
